package com.dgut.healthreportmanage.controller;

import com.dgut.healthreportmanage.pojo.Admin;
import com.dgut.healthreportmanage.pojo.AdminEntity;
import com.dgut.healthreportmanage.pojo.Report;
import com.dgut.healthreportmanage.pojo.User;
import com.dgut.healthreportmanage.service.AdminService;
import com.dgut.healthreportmanage.service.ReportService;
import com.dgut.healthreportmanage.service.UserService;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AdminController {
    @Resource(name="authenticationManager")
    private AuthenticationManager authenticationManager;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private UserService userService;
    //腾讯云防水墙
    static final String SECRET_ID = "AKIDh5E6i36sNbYEemdDVXImzvay5vTkjRt3";
    static final String SECRET_KEY = "uXu0pMddMoywc190astd6wVmnX0qVw72";
    static final long APP_ID = 2072922296L;
    static final String APP_SECRET_KEY = "0PkpcZ6xgoHrb-CIYhzfF2A**";
    //请求域名captcha.tencentcloudapi.com
    private static final String URI = "captcha.tencentcloudapi.com";

    @RequestMapping(value = "/admin/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping(value = "/admin/home")
    public ModelAndView toHome(){
        //获取登录的用户名
        Object principal= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String adminName=null;
        if(principal instanceof AdminEntity) {
            adminName=((AdminEntity)principal).getUsername();
        }else {
            adminName=principal.toString();
        }
        List<Report> allReports = reportService.getAllReports();
        List<User> allUsers = userService.getAllUsers();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("adminName", adminName);
        modelAndView.addObject("allReports", allReports);
        modelAndView.addObject("allUsers", allUsers);
        modelAndView.setViewName("adminHome");
        return modelAndView;
    }

    public long postTicket(String ticket, String userIp, String randstr){
        Long result = 0L;
        try{
            Credential cred = new Credential(SECRET_ID, SECRET_KEY);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(URI);

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setCaptchaType(9L);
            req.setTicket(ticket);
            req.setUserIp(userIp);
            req.setRandstr(randstr);
            req.setCaptchaAppId(APP_ID);
            req.setAppSecretKey(APP_SECRET_KEY);
            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            result = resp.getCaptchaCode();
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return result;
    }

    @RequestMapping(value = "/postTicket")
    public ModelAndView login(String adminName, String password, String ticket, String randstr,
                        HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
        String userIp = request.getLocalAddr();
        ModelAndView modelAndView = new ModelAndView();
        //验证ticket
        long result = postTicket(ticket, userIp, randstr);
        if (result == 1) {
            int loginResult = adminService.login(adminName, password);
            if (loginResult == 2){
                modelAndView.addObject("message", "账号已冻结");
            }
            else if (loginResult == 0) {
                modelAndView.addObject("message", "账号或密码错误");
            }
            else{
                if (loginResult == 3) {
                    httpSession.setAttribute("isSysAdmin", true);
                }
                //spring security验证
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(adminName, password);
                token.setDetails(new WebAuthenticationDetails(request));
                Authentication authentication = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                modelAndView.setViewName("redirect:/admin/home");
                return modelAndView;
            }
        }
        else modelAndView.addObject("message", "验证不通过，请重试");
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping(value = "/admin/allAdmins")
    public ModelAndView getAllAdmin(){
        List<Admin> allAdmins = adminService.getAllAdmins();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("allAdmins",allAdmins);
        modelAndView.setViewName("allAdmins");
        return modelAndView;
    }

    @RequestMapping(value = "/admin/update")
    public String update(Admin admin){
        adminService.update(admin);
        return "redirect:/admin/allAdmins";
    }

    @RequestMapping(value = "/admin/freeze/{adminId}")
    public String freeze(@PathVariable int adminId){
        adminService.freeze(adminId);
        return "redirect:/admin/allAdmins";
    }

    @RequestMapping(value = "/admin/delete/{adminId}")
    public String delete(@PathVariable int adminId){
        adminService.delete(adminId);
        return "redirect:/admin/allAdmins";
    }
}
